package com.speech.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import com.speech.MyApplication;
import com.speech.R;
import com.speech.constant.PrefsConstant;
import com.speech.db.SharedPreferenceHelper;
import com.speech.entity.BaseEntity;
import com.speech.http.BaseCallback;
import com.speech.net.BasicCallBack;
//import com.speech.net.HttpCommunicationManager;
import com.speech.net.constant.EnumReqestActionCode;
import com.speech.net.entity.MessageC2S;
import com.speech.net.entity.MessageC2SBuilder;
import com.speech.net.entity.MessageS2C;
import com.speech.result.Result;
import com.speech.utils.DeviceUtil;
import com.speech.utils.JsonProcessor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import retrofit2.Call;

public class FollowWeixinGZHActivity extends BaseActivity {

    private EditText edt;

    private ImageView img_QRCode;
    private TextView tv_save;

    private SweetAlertDialog dialog;

    private View.OnClickListener listener_save_QRCode = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.gongzhonghao);
            MediaStore.Images.Media.insertImage(FollowWeixinGZHActivity.this.getContentResolver(), bitmap, null, null);
            saveImageToGallery(this, bitmap);
            Toast.makeText(FollowWeixinGZHActivity.this,"二维码已保存到本地",Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_follow_gongzhonghao);

        _initView();

        //二维码点击保存
        img_QRCode.setOnClickListener(listener_save_QRCode);
        tv_save.setOnClickListener(listener_save_QRCode);


        edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (edt.getText() != null) {
                    String str = edt.getText().toString();
                    if (str.length() == 6) {


                        //TODO: 接口请求 完成某任务
//                        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(FollowWeixinGZHActivity.this, EnumReqestActionCode.完成某任务, "{\"mcode\":\"" + str + "\"}");
//                        String json = JsonProcessor.StcGetJson(msg_c2s);
//                        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(FollowWeixinGZHActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//                            @Override
//                            public void success(MessageS2C msg_s2c) {
//                                new SweetAlertDialog(FollowWeixinGZHActivity.this, SweetAlertDialog.SUCCESS_TYPE)
//                                        .setTitleText(msg_s2c.strMsgUI)
//                                        .setConfirmText("OK")
//                                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                                            @Override
//                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                                sweetAlertDialog.dismiss();
//                                                finish();
//                                            }
//                                        })
//                                        .show();
//                                edt.setText("");
//                            }
//
//                            @Override
//                            public void fail(MessageS2C msg_s2c) {
//                                new SweetAlertDialog(FollowWeixinGZHActivity.this, SweetAlertDialog.ERROR_TYPE)
//                                        .setTitleText(msg_s2c.strMsgUI)
//                                        .setConfirmText("OK")
//                                        .show();
//                                edt.setText("");
//                            }
//                        }));


                        String uid,token;
                        SharedPreferenceHelper spf = new SharedPreferenceHelper(FollowWeixinGZHActivity.this, PrefsConstant.FILE_USER_INFO);
                        String lUID = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, "");
                        uid = lUID;
                        String lToken = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, "");
                        token = lToken;
                        Call<Result<BaseEntity>> call = MyApplication.getInstance().getApiService()
                                .mission(uid,token, DeviceUtil.getDeviceID(FollowWeixinGZHActivity.this)
                                ,"1","112391");
                        call.enqueue(new BaseCallback<BaseEntity>() {
                            @Override
                            public void onSuccess(BaseEntity baseEntity) {
//                                dialog = new SweetAlertDialog(FollowWeixinGZHActivity.this, SweetAlertDialog.SUCCESS_TYPE)
//                                        .setTitleText("任务完成")
//                                        .setConfirmText("OK")
//                                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                                            @Override
//                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                                sweetAlertDialog.dismiss();
//                                                finish();
//                                            }
//                                        });
//                                        dialog.show();
                                edt.setText("");
                            }

                            @Override
                            public void onAbnormal(String msg) {
//                                dialog = new SweetAlertDialog(FollowWeixinGZHActivity.this, SweetAlertDialog.ERROR_TYPE)
//                                        .setTitleText(msg)
//                                        .setConfirmText("OK");
//                                        dialog.show();
                                edt.setText("");
                            }

                            @Override
                            public void onFailure(String msg) {
//                                dialog = new SweetAlertDialog(FollowWeixinGZHActivity.this, SweetAlertDialog.ERROR_TYPE)
//                                        .setTitleText(msg)
//                                        .setConfirmText("OK");
//                                        dialog.show();
                                edt.setText("");
                            }
                        });
                    }
                }
            }
        });


    }

    private void _initView() {
        edt = findViewById(R.id.edt_follow_gongzhonghao);
        img_QRCode = findViewById(R.id.img_follow_gongzhonghao_qrcode);
        tv_save = findViewById(R.id.tv_follow_gongzhonghao_save);
    }


    private void saveImageToGallery(OnClickListener context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "voc");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(getContentResolver(),
                file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
            .parse("file://" + file.getAbsolutePath())));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null){
            dialog.dismissWithAnimation();
        }
    }
}
